<?php

namespace App\Jobs;

use App\Http\Controllers\Api\WeChatControllerBase;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class SendTemplateMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $data;
    protected $instance;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($param,$instance)
    {
        //
        $this->data = $param;
        $this->instance = $instance;
    }

    /**
     * Execute the job.
     *[
        'touser' => 'user-openid',
        'template_id' => 'template-id',
        'page' => 'index',
        'form_id' => 'form-id',
        'data' => [
        'keyword1' => 'VALUE',
        'keyword2' => 'VALUE2',
        // ...
        ],
     ]
     * @return void
     */
    public function handle()
    {
        //
        try{
            $wx = new WeChatControllerBase();
            $app = $wx->getAppInstance();
            $res = $app->template_message->send($this->data);
            Log::info('template_message_result:'.json_encode($res,JSON_UNESCAPED_UNICODE));
            $this->instance->status = 0;
            $this->instance->save();
        }catch (\Exception $e) {
            Log::error('send template failed !'.($e->getCode()).($e->getMessage()));
        }

    }
}
